package com.lingshi.yingzaitownmap.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingshi.yingzaitownmap.entity.domain.Shops;
import com.lingshi.yingzaitownmap.entity.dto.PageDTO;
import com.lingshi.yingzaitownmap.entity.result.Result;
import com.lingshi.yingzaitownmap.service.ShopsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * 商铺相关接口
 */
@RestController
@RequestMapping("/api/v1/shops")
@Slf4j
@RequiredArgsConstructor
@Validated
public class ShopsControler {

    private final ShopsService shopsService;

    /**
     * 根据ID查询商铺信息
     */
    @GetMapping("/{id}")
    public Result getShopById(@PathVariable String id) {
        // 日志
        log.info("根据ID查询商铺,{}",id);
        // id非空判断
        if(StrUtil.isBlank(id)){
            throw new RuntimeException("id不能为空");
        }
        // 查询
        Shops shopInfo = shopsService.query().eq("id", id).one();
        // 数据非空判断
        if(shopInfo == null){
            throw new RuntimeException("商铺 id错误");
        }
        // 封装返回信息
        HashMap<String, Object> result = new HashMap<>();
        result.put("id", shopInfo.getId());
        result.put("name", shopInfo.getName());
        result.put("cover", shopInfo.getCover());
        result.put("desc", shopInfo.getDescription());
        // 返回
        return Result.success(result);
    }


    /**
     * 分页查询 商铺信息
     */
    @GetMapping
    public Result getShops(@RequestBody PageDTO pageDTO){
        // 日志
        log.info("分页查询商铺信息,{}",pageDTO);
        // 判断是否有关键词
        Boolean hasKeyword = StrUtil.isNotBlank(pageDTO.getKeyword());
        // 查询
        Page<Shops> page = shopsService.query()
                .select("id","name","cover")
                .like(hasKeyword, "name", pageDTO.getKeyword())
                .or()
                .like(hasKeyword, "description", pageDTO.getKeyword())
                .or()
                .like(hasKeyword, "address", pageDTO.getKeyword())
                .page(new Page<>(pageDTO.getPage(), pageDTO.getPageSize()));
        // 封装返回信息
        HashMap<String, Object> result = new HashMap<>();
        result.put("list", page.getRecords());
        result.put("total", page.getRecords().size());
        // 返回
        return Result.success(result);
    }

}
